package com.capgemini.fs.presentation.user.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.capgemini.fs.app.ekms.common.Constants;
import com.capgemini.fs.app.ekms.model.Group;
import com.capgemini.fs.app.ekms.model.Role;
import com.capgemini.fs.app.ekms.model.User;
import com.capgemini.fs.app.ekms.service.UserService;

public class UserListSearchAction extends Action {
	private UserService userListSearchUserService;

	public UserService getUserListSearchUserService() {
		return userListSearchUserService;
	}

	public void setUserListSearchUserService(
			UserService userListSearchUserService) {
		this.userListSearchUserService = userListSearchUserService;
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = new JSONObject();

		Integer status = null;
		if (request.getParameter("active").equals("0")) {
			status = Constants.USER_STATUS_ACTIVE;
		} else if (request.getParameter("active").equals("1")) {
			status = Constants.USER_STATUS_INACTIVE;
		}

		// determine category
		int category = 0;
		
		if ("Trainee".equalsIgnoreCase(request.getParameter("category"))) {
			category = Constants.USER_MEMBERTYPE_TRAINEE;
		} else {
			category = Constants.USER_MEMBERTYPE_EMPLOYEE;
		}

		// get role data
		String[] roles = request.getParameterValues("role");
		List<String> role = new ArrayList<String>();
		if (roles != null) {
			for (int i = 0; i < roles.length; i++) {
				role.add(roles[i]);
			}
		}

		String[] groups = request.getParameterValues("group");
		List<String> group = new ArrayList<String>();
		if (groups != null) {
			for (int i = 0; i < groups.length; i++) {
				group.add(groups[i]);
			}
		}

		List<User> userList = null;
		boolean isSuccess = true;

		try {
			userList = userListSearchUserService.queryUser(request
					.getParameter("firstName"), request
					.getParameter("lastName"),
					request.getParameter("userName"), status, request
							.getParameter("email"), request
							.getParameter("phoneNo"), category, role, group);
		} catch (Exception e) {
			isSuccess = false;
			e.printStackTrace();
			return null;
		}
		// change action to JSON
		for (int i = 0; i < userList.size(); i++) {
			User u = userList.get(i);

			JSONObject jo = new JSONObject();

			jo.put("id", u.getId());
			jo.put("userName", u.getUserName());
			jo.put("firstName", u.getFirstName());
			jo.put("lastName", u.getLastName());
			jo.put("email", u.getEmail());
			jo.put("userCategory", u.getMemberType());
			jo.put("active", u.getStatus());
			jo.put("phoneNo", u.getPhoneNo());
			// add group info
			Iterator<Group> groups1 = u.getGroups().iterator();
			String joGroups = "";
			while (groups1.hasNext()) {
				Group joGroup = groups1.next();
				joGroups += joGroup.getGroupName() + "/ ";
			}
			if (joGroups.length() > 2) {
				joGroups = joGroups.substring(0, joGroups.length() - 2);
			}
			// add role info
			Iterator<Role> roles1 = u.getRoles().iterator();
			String joRoles = "";
			while (roles1.hasNext()) {
				Role joRole = roles1.next();
				joRoles += joRole.getName() + "/ ";
			}
			if (joRoles.length() > 2) {
				joRoles = joRoles.substring(0, joRoles.length() - 2);
			}
			jo.put("roles", joGroups);
			jo.put("groups", joRoles);

			jsonArray.add(jo);
		}
		jsonObject.put("data", jsonArray);
		jsonObject.put("isSuccess", isSuccess);

		try {
			// Get response printer
			PrintWriter out = response.getWriter();

			// Print the JSON object to client browser
			out.print(jsonObject.toString());

			// Flush the data from server memory to client browser
			out.flush();

			// Close data socket
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

}
